package com.hu.common.util.adm;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author 355760
 * @ClassName NetUtil
 * @Description 网络工具
 */
public class NetUtil {

    /**
     * 获取远程访问IP
     * @param request
     * @return
     */
    public static String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    // 获取最后一个ip地址（可能有多个ip）
    public static long getHostIP() throws SocketException {

        Enumeration<NetworkInterface> allNetInterfaces = null;
        byte resultIP = 0;

        allNetInterfaces = NetworkInterface.getNetworkInterfaces();

        InetAddress ip;
        while (true)
        {
            assert allNetInterfaces != null;
            if (!allNetInterfaces.hasMoreElements()) {
                break;
            }
            NetworkInterface netInterface = allNetInterfaces.nextElement();
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements())
            {
                ip = addresses.nextElement();
                if (ip instanceof Inet4Address && !ip.getHostAddress().equals("127.0.0.1"))
                {
                    byte[] address = ip.getAddress();
                    resultIP = address[address.length - 1];

                    return resultIP < 0 ? (256 + resultIP) : resultIP;
                }
            }

        }
        return resultIP;

    }
}
